<template>
  <section id="feedback" class="py-24 md:py-32" :style="{ backgroundColor: bgColor }">
    <div class="container mx-auto px-4 sm:px-6 lg:px-8">
      <div class="max-w-3xl mx-auto">
        <!-- 标题区域 -->
        <div class="text-center mb-12" v-if="showHeader">
          <span :style="{ color: primaryColor }" class="font-medium">意见反馈</span>
          <h2 class="text-[clamp(1.75rem,4vw,2.5rem)] font-bold mt-2 mb-4 text-gray-800">您的建议对我们很重要</h2>
          <p class="text-lg text-gray-600 leading-relaxed">如果您有任何建议或问题，欢迎告诉我们，我们会尽快回复您</p>
        </div>

        <!-- 数据加载错误提示 -->
        <div v-if="dataLoadError" class="mb-8 p-4 bg-red-50 text-red-700 rounded-lg text-center">
          <i class="fa fa-exclamation-circle mr-2"></i>{{ dataLoadError }}
          <button type="button" class="ml-2 text-sm text-primary underline hover:text-primary/80" @click="refresh"
            :disabled="loading">
            {{ loading ? '刷新中...' : '重新加载' }}
          </button>
        </div>

        <!-- 表单容器或加载状态 -->
        <div v-if="!loading">
          <div class="bg-gray-50 p-8 shadow-md transition-all duration-300"
            :style="{ borderRadius: `${formRadius}px` }">
            <form @submit.prevent="handleSubmit">
              <!-- 姓名和邮箱 -->
              <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
                <div>
                  <label :for="`${idPrefix}-name`" class="block text-gray-800 mb-2">
                    姓名
                    <span v-if="fields.name.required" class="text-red-500">*</span>
                  </label>
                  <input type="text" :id="`${idPrefix}-name`"
                    class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:border-primary transition-all duration-300"
                    :class="{ 'focus:ring-primary/50': true }" placeholder="您的姓名" v-model="formData.name"
                    :required="fields.name.required">
                </div>
                <div>
                  <label :for="`${idPrefix}-email`" class="block text-gray-800 mb-2">
                    邮箱
                    <span v-if="fields.email.required" class="text-red-500">*</span>
                  </label>
                  <input type="email" :id="`${idPrefix}-email`"
                    class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:border-primary transition-all duration-300"
                    :class="{ 'focus:ring-primary/50': true }" placeholder="您的邮箱" v-model="formData.email"
                    :required="fields.email.required">
                </div>
              </div>

              <!-- 反馈类型 -->
              <div class="mb-6" v-if="showFeedbackType">
                <label :for="`${idPrefix}-type`" class="block text-gray-800 mb-2">
                  反馈类型
                  <span v-if="fields.type.required" class="text-red-500">*</span>
                </label>
                <select :id="`${idPrefix}-type`"
                  class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:border-primary transition-all duration-300"
                  :class="{ 'focus:ring-primary/50': true }" v-model="formData.type" :required="fields.type.required">
                  <option value="">请选择反馈类型</option>
                  <option v-for="option in feedbackTypeOptions" :key="option.value" :value="option.value">
                    {{ option.label }}
                  </option>
                </select>
              </div>

              <!-- 主题 -->
              <div class="mb-6">
                <label :for="`${idPrefix}-subject`" class="block text-gray-800 mb-2">
                  主题
                  <span v-if="fields.subject.required" class="text-red-500">*</span>
                </label>
                <input type="text" :id="`${idPrefix}-subject`"
                  class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:border-primary transition-all duration-300"
                  :class="{ 'focus:ring-primary/50': true }" placeholder="反馈主题" v-model="formData.subject"
                  :required="fields.subject.required">
              </div>

              <!-- 反馈内容 -->
              <div class="mb-6">
                <label :for="`${idPrefix}-message`" class="block text-gray-800 mb-2">
                  反馈内容
                  <span v-if="fields.message.required" class="text-red-500">*</span>
                </label>
                <textarea :id="`${idPrefix}-message`" rows="5"
                  class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:border-primary transition-all duration-300"
                  :class="{ 'focus:ring-primary/50': true }" placeholder="请详细描述您的反馈内容" v-model="formData.message"
                  :required="fields.message.required"></textarea>
              </div>

              <!-- 上传附件 -->
              <div class="mb-6" v-if="showFileUpload">
                <label class="block text-gray-800 mb-2">
                  上传附件
                  <span class="text-gray-500 text-sm ml-2">(可选)</span>
                </label>
                <div
                  class="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center hover:border-primary/50 transition-all duration-300 cursor-pointer"
                  @click="triggerFileUpload" @dragover.prevent @dragenter.prevent @dragleave.prevent
                  @drop.prevent="handleFileDrop">
                  <i class="fa fa-cloud-upload text-3xl text-gray-400 mb-2"></i>
                  <p class="text-gray-600 mb-2">点击或拖拽文件到此处上传</p>
                  <p class="text-gray-400 text-sm">支持JPG、PNG、PDF格式，最大5MB</p>
                  <input type="file" class="hidden" :id="`${idPrefix}-file-upload`" :accept="fileTypes"
                    @change="handleFileSelect" :multiple="allowMultipleFiles">
                  <button type="button" @click="triggerFileUpload"
                    class="mt-4 px-4 py-2 border text-primary rounded-lg hover:bg-primary/5 transition-all duration-300"
                    :style="{ borderColor: primaryColor }">
                    选择文件
                  </button>
                </div>

                <!-- 已上传文件列表 -->
                <div v-if="selectedFiles.length > 0" class="mt-4">
                  <p class="text-gray-700 mb-2">已选择文件:</p>
                  <div class="space-y-2">
                    <div v-for="(file, index) in selectedFiles" :key="index"
                      class="flex items-center p-2 bg-white rounded">
                      <i class="fa fa-file-o mr-2" :style="{ color: primaryColor }"></i>
                      <span class="flex-1 truncate">{{ file.name }}</span>
                      <span class="text-gray-500 text-sm mr-3">{{ formatFileSize(file.size) }}</span>
                      <button type="button" class="text-gray-400 hover:text-red-500" @click="removeFile(index)">
                        <i class="fa fa-times"></i>
                      </button>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 隐私政策同意 -->
              <div class="mb-6" v-if="showPrivacyAgreement">
                <label class="flex items-start">
                  <input type="checkbox" class="w-4 h-4 mt-1 border-gray-300 rounded transition-all duration-300"
                    :class="{ 'focus:ring-primary/50': primaryColor }" :style="{ color: primaryColor }"
                    v-model="formData.agreePrivacy" :required="fields.agreePrivacy.required">
                  <span class="ml-2 text-gray-700">
                    我同意智联科技根据隐私政策处理我的个人信息
                  </span>
                </label>
              </div>

              <!-- 提交按钮 -->
              <button type="submit"
                class="px-8 py-3 text-white rounded-lg hover:opacity-90 transition-all duration-300 disabled:opacity-60 disabled:cursor-not-allowed"
                :disabled="isSubmitting || loading" :style="{ backgroundColor: primaryColor }">
                <span v-if="!isSubmitting">提交反馈</span>
                <span v-if="isSubmitting">
                  <i class="fa fa-spinner fa-spin mr-2"></i>提交中...
                </span>
              </button>

              <!-- 提交结果提示 -->
              <div v-if="submitStatus" class="mt-4 p-4 rounded-lg" :class="{
                'bg-green-50 text-green-700': submitStatus === 'success',
                'bg-red-50 text-red-700': submitStatus === 'error'
              }">
                <p v-if="submitStatus === 'success'">
                  <i class="fa fa-check-circle mr-2"></i>反馈提交成功，感谢您的宝贵意见！
                </p>
                <p v-if="submitStatus === 'error'">
                  <i class="fa fa-exclamation-circle mr-2"></i>提交失败，请稍后再试
                </p>
              </div>
            </form>
          </div>
        </div>
        <!-- 数据加载中状态 -->
        <div v-else class="flex flex-col items-center justify-center p-12 bg-gray-50 rounded-lg shadow-md">
          <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-primary mb-4"></div>
          <p class="text-gray-600">加载表单配置中...</p>
        </div>
      </div>
    </div>
  </section>
</template>

<script>
export default {
  name: 'FeedbackForm',
  // 低代码平台元数据 - 移除语言相关配置
  lowcode: {
    meta: {
      name: 'feedback-form',
      displayName: '反馈表单',
      description: '用于收集用户意见和反馈的表单组件',
      icon: 'fa-pencil',
      category: '表单组件',
      version: '1.0.0',
      isContainer: false
    },

    configPanel: [{ title: '基本配置', fields: [{ name: 'primaryColor', label: '主题色', type: 'color', defaultValue: '#165DFF' }, { name: 'bgColor', label: '背景色', type: 'color', defaultValue: '#ffffff' }, { name: 'showHeader', label: '显示标题区域', type: 'boolean', defaultValue: true }, { name: 'dataSourceUrl', label: 'API接口地址', type: 'text', defaultValue: '', description: '用于获取表单配置的API地址' }, { name: 'autoLoad', label: '自动加载数据', type: 'boolean', defaultValue: true }] },
    {
      title: '表单配置',
      fields: [
        {
          name: 'formRadius',
          label: '表单圆角',
          type: 'number',
          min: 0,
          max: 20,
          defaultValue: 8
        },
        {
          name: 'idPrefix',
          label: 'ID前缀',
          type: 'text',
          defaultValue: 'feedback',
          description: '用于表单元素ID的前缀，避免重复'
        },
        {
          name: 'showFeedbackType',
          label: '显示反馈类型',
          type: 'boolean',
          defaultValue: true
        },
        {
          name: 'showFileUpload',
          label: '显示文件上传',
          type: 'boolean',
          defaultValue: true
        },
        {
          name: 'showPrivacyAgreement',
          label: '显示隐私协议',
          type: 'boolean',
          defaultValue: true
        },
        {
          name: 'allowMultipleFiles',
          label: '允许多文件上传',
          type: 'boolean',
          defaultValue: false
        }
      ]
    },
    {
      title: '字段配置',
      fields: [
        {
          name: 'fields',
          label: '字段设置',
          type: 'object',
          description: '配置各字段是否必填',
          defaultValue: {
            name: { required: true },
            email: { required: true },
            type: { required: true },
            subject: { required: true },
            message: { required: true },
            agreePrivacy: { required: true }
          }
        },
        {
          name: 'feedbackTypeOptions',
          label: '反馈类型选项',
          type: 'array',
          description: '自定义反馈类型选项',
          defaultValue: [
            { label: '功能建议', value: 'suggestion' },
            { label: '问题反馈', value: 'bug' },
            { label: '投诉建议', value: 'complaint' },
            { label: '表扬鼓励', value: 'praise' },
            { label: '其他', value: 'other' }
          ]
        }
      ]
    }
    ],

    events: [{ name: 'submit', label: '表单提交', description: '表单提交时触发', parameters: [{ name: 'formData', type: 'object', description: '表单数据' }, { name: 'files', type: 'array', description: '上传的文件列表' }] }, { name: 'submitSuccess', label: '提交成功', description: '表单提交成功后触发', parameters: [{ name: 'response', type: 'object', description: '提交成功的响应数据' }] }, { name: 'submitError', label: '提交失败', description: '表单提交失败时触发', parameters: [{ name: 'error', type: 'object', description: '错误信息' }] }, { name: 'fileUpload', label: '文件上传', description: '文件上传时触发', parameters: [{ name: 'files', type: 'array', description: '上传的文件列表' }] }, { name: 'dataLoaded', label: '数据加载完成', description: '从数据源加载表单配置完成后触发', parameters: [{ name: 'data', type: 'object', description: '加载的表单配置数据' }] }, { name: 'dataLoadError', label: '数据加载失败', description: '从数据源加载表单配置失败时触发', parameters: [{ name: 'error', type: 'object', description: '错误信息' }] }],

    actions: [{ name: 'resetForm', label: '重置表单', description: '清空表单内容' }, { name: 'submitForm', label: '提交表单', description: '触发表单提交' }, { name: 'refresh', label: '刷新数据', description: '重新从数据源加载表单配置数据' }]
  },

  props: {
    // 颜色配置
    primaryColor: {
      type: String,
      default: '#165DFF'
    },
    bgColor: {
      type: String,
      default: '#ffffff'
    },

    // 数据源配置
    dataSourceUrl: {
      type: String,
      default: ''
    },
    autoLoad: {
      type: Boolean,
      default: true
    },

    children: {
      type: Array,
      default: () => []
    },
    // 表单配置
    formRadius: {
      type: Number,
      default: 8,
      validator: (value) => value >= 0 && value <= 20
    },
    idPrefix: {
      type: String,
      default: 'feedback'
    },
    showHeader: {
      type: Boolean,
      default: true
    },
    showFeedbackType: {
      type: Boolean,
      default: true
    },
    showFileUpload: {
      type: Boolean,
      default: true
    },
    showPrivacyAgreement: {
      type: Boolean,
      default: true
    },
    allowMultipleFiles: {
      type: Boolean,
      default: false
    },

    // 字段配置
    fields: {
      type: Object,
      default: () => ({
        name: { required: true },
        email: { required: true },
        type: { required: true },
        subject: { required: true },
        message: { required: true },
        agreePrivacy: { required: true }
      })
    },
    feedbackTypeOptions: {
      type: Array,
      default: () => [
        { label: '功能建议', value: 'suggestion' },
        { label: '问题反馈', value: 'bug' },
        { label: '投诉建议', value: 'complaint' },
        { label: '表扬鼓励', value: 'praise' },
        { label: '其他', value: 'other' }
      ]
    }
  },

  data() {
    return {
      // 表单数据
      formData: {
        name: '',
        email: '',
        type: '',
        subject: '',
        message: '',
        agreePrivacy: false
      },
      // 选中的文件
      selectedFiles: [],
      // 提交状态
      isSubmitting: false,
      submitStatus: null, // null, 'success', 'error'
      // 数据源相关状态
      loading: false,
      dataLoadError: null,
      formConfig: null
    };
  },

  computed: {
    // 允许上传的文件类型
    fileTypes() {
      return 'image/jpeg, image/png, application/pdf';
    }
  },

  watch: {
    // 监听数据源URL变化
    dataSourceUrl(newVal) {
      if (this.autoLoad && newVal) {
        this.loadDataFromSource();
      }
    }
  },

  mounted() {
    // 组件挂载时，如果配置了自动加载且有数据源URL，则加载数据
    if (this.autoLoad && this.dataSourceUrl) {
      this.loadDataFromSource();
    }
  },

  methods: {
    /**
     * 从数据源加载表单配置数据
     */
    async loadDataFromSource() {
      if (!this.dataSourceUrl) {
        return;
      }

      this.loading = true;
      this.dataLoadError = null;

      try {
        const response = await fetch(this.dataSourceUrl);
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();
        // 验证数据格式
        if (this.validateFormConfig(data)) {
          this.formConfig = data;
          // 应用加载的配置
          this.applyFormConfig(data);
          // 触发数据加载完成事件
          this.$emit('dataLoaded', data);
        } else {
          throw new Error('Invalid form configuration data');
        }
      } catch (error) {
        console.error('Failed to load form configuration:', error);
        this.dataLoadError = error.message || '加载失败';
        this.$emit('dataLoadError', { error: this.dataLoadError });
      } finally {
        this.loading = false;
      }
    },

    /**
     * 验证表单配置数据格式
     */
    validateFormConfig(data) {
      if (!data || typeof data !== 'object') {
        return false;
      }
      // 基本验证，确保必要的字段存在
      return true;
    },

    /**
     * 应用加载的表单配置
     */
    applyFormConfig(config) {
      // 这里可以根据实际需求应用配置
      // 例如设置表单字段、选项等
      if (config.fields) {
        // 可以在这里更新表单字段配置
      }
      if (config.feedbackTypeOptions) {
        // 可以在这里更新反馈类型选项
      }
    },

    /**
     * 刷新表单配置数据
     */
    refresh() {
      if (this.dataSourceUrl) {
        this.loadDataFromSource();
      }
    },

    /**
     * 触发文件上传
     */
    triggerFileUpload() {
      document.getElementById(`${this.idPrefix}-file-upload`).click();
    },

    /**
     * 处理文件选择
     */
    handleFileSelect(e) {
      const files = Array.from(e.target.files);
      this.addFiles(files);
      // 重置input值，允许重复选择同一文件
      e.target.value = '';
    },

    /**
     * 处理文件拖放
     */
    handleFileDrop(e) {
      const files = Array.from(e.dataTransfer.files);
      this.addFiles(files);
    },

    /**
     * 添加文件到列表
     */
    addFiles(files) {
      if (!files || files.length === 0) return;

      // 过滤不支持的文件类型
      const validFiles = files.filter(file => {
        return this.fileTypes.includes(file.type);
      });

      // 检查文件大小
      const filteredFiles = validFiles.filter(file => {
        // 5MB限制
        return file.size <= 5 * 1024 * 1024;
      });

      // 如果不允许多文件，只保留最后一个
      const finalFiles = this.allowMultipleFiles
        ? [...this.selectedFiles, ...filteredFiles]
        : filteredFiles.slice(-1);

      this.selectedFiles = finalFiles;
      this.$emit('fileUpload', finalFiles);
    },

    /**
     * 移除文件
     */
    removeFile(index) {
      this.selectedFiles.splice(index, 1);
    },

    /**
     * 格式化文件大小
     */
    formatFileSize(bytes) {
      if (bytes === 0) return '0 Bytes';
      const k = 1024;
      const sizes = ['Bytes', 'KB', 'MB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    },

    /**
     * 处理表单提交
     */
    handleSubmit() {
      this.isSubmitting = true;
      this.submitStatus = null;

      // 触发提交事件
      this.$emit('submit', this.formData, this.selectedFiles);

      // 模拟API提交
      setTimeout(() => {
        // 实际项目中这里会调用API提交数据
        const success = true; // 模拟成功/失败

        if (success) {
          this.submitStatus = 'success';
          this.$emit('submitSuccess', { message: '提交成功' });
          // 成功后重置表单
          setTimeout(() => {
            this.resetForm();
          }, 3000);
        } else {
          this.submitStatus = 'error';
          this.$emit('submitError', { message: '提交失败' });
        }

        this.isSubmitting = false;
      }, 1500);
    },

    /**
     * 重置表单
     */
    resetForm() {
      this.formData = {
        name: '',
        email: '',
        type: '',
        subject: '',
        message: '',
        agreePrivacy: false
      };
      this.selectedFiles = [];
      this.submitStatus = null;
    },

    /**
     * 手动提交表单
     */
    submitForm() {
      // 触发表单验证和提交
      const formElement = this.$el.querySelector('form');
      if (formElement.checkValidity()) {
        this.handleSubmit();
      } else {
        // 触发浏览器默认验证提示
        formElement.reportValidity();
      }
    }
  }
};
</script>